package com.qys.livesMall.event.listener;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qys.livesMall.anchor.event.LiveEndEvent;
import com.qys.livesMall.anchor.event.pojo.LiveEndEventPOJO;
import com.qys.livesMall.anchor.mapper.AnchorRewardConfigMapper;
import com.qys.livesMall.anchor.model.entity.AnchorRewardConfig;
import com.qys.livesMall.cache.RedisCache;
import com.qys.livesMall.finance.enums.AccountBusinessTypeEnum;
import com.qys.livesMall.finance.model.dto.FinancePayDTO;
import com.qys.livesMall.finance.service.FinanceBusinessService;
import com.qys.livesMall.finance.util.BusinessNoUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;


/**
 * 直播结束事件订阅
 * @author yxh
 */
@Slf4j
@Component
public class LiveEndListener implements ApplicationListener<LiveEndEvent> {


    @Resource
    private RedisCache redisCache;
    @Resource
    private FinanceBusinessService financeBusinessService;
    @Resource
    private AnchorRewardConfigMapper anchorRewardConfigMapper;

    private final static String REDIS_LOCK_KEY = "LiveEndEvent_lock";


    @Async
    @Override
    public void onApplicationEvent(LiveEndEvent event) {
        LiveEndEventPOJO liveEnd = (LiveEndEventPOJO) event.getSource();
        boolean lock = redisCache.lock(REDIS_LOCK_KEY + liveEnd.getUserId(), 1, 2);
        if(!lock){
            return;
        }
        //判断是否达到奖励标准
        AnchorRewardConfig anchorRewardConfig = anchorRewardConfigMapper.selectOne(Wrappers.<AnchorRewardConfig>lambdaQuery()
                .eq(AnchorRewardConfig::getAwardType, 4)
                .le(AnchorRewardConfig::getAwardCondition, liveEnd.getLivesDuration()/60)
                .orderByDesc(AnchorRewardConfig::getAwardCondition)
                .last("limit 1")
        );

        if(anchorRewardConfig != null){
            //判断是否领取过该阶段奖励
            int rewarded = anchorRewardConfigMapper.rewardJudgment(anchorRewardConfig.getConId(), liveEnd.getUserId(), false);
            if(rewarded > 0){
                return;
            }
            FinancePayDTO payDTO = new FinancePayDTO();
            payDTO.setUserId(liveEnd.getUserId());
            payDTO.setBusinessType(AccountBusinessTypeEnum.TIME_BONUS_FOR_FIRST_LIVE_BROADCAST);
            payDTO.setAmountIncurred(anchorRewardConfig.getAwardAmount());
            payDTO.setBusinessNo(BusinessNoUtil.get(AccountBusinessTypeEnum.TIME_BONUS_FOR_FIRST_LIVE_BROADCAST));
            payDTO.setDescription("主播首次直播时长达标奖励");
            financeBusinessService.pay(payDTO);
            if (payDTO.getSuccess()) {
                anchorRewardConfigMapper.keepRecords(anchorRewardConfig.getConId(), liveEnd.getUserId());
                log.info("主播首次直播时长达标奖励成功, 奖励配置id:{}，userId:{}", anchorRewardConfig.getConId(), liveEnd.getUserId());
            } else {
                log.info("主播首次直播时长达标奖励失败, 奖励配置id:{}，userId:{}，原因：{}", anchorRewardConfig.getConId(), liveEnd.getUserId(), payDTO.getMessage());
            }
        }
        redisCache.deleteObject(REDIS_LOCK_KEY + liveEnd.getUserId());
    }

}
